<script>
import { h } from 'vue';
import { useFullscreen } from '@vueuse/core';
import loadScript from '../../utils/loadScript.js';
import mapGetter from './js/AMapMapGetter.js';

export default {
  name: 'map-core',
  emits: ['ready'],
  props: {
    /* 地图是否使用单例模式，比如表单，弹窗内的地图应该使用单例模式以避免反复渲染地图引起内存泄露 */
    singleMode: { type: Boolean, default: false },
    mapOptions: { type: [Object, Function], default: () => ({}) },
  },
  data() {
    return {
      ready: false,
    };
  },
  async mounted() {
    await loadScript('//webapi.amap.com/maps?v=1.4.15&key=d99cf0fc41f79425572e5b1298c0f21c');
    const option = typeof this.mapOptions === 'function' ? this.mapOptions() : this.mapOptions;
    this.map = await (this.singleMode === true ? mapGetter.getSingleMap : mapGetter.getMap)(option);
    this.mapContainer = this.map.getContainer();
    if (this.$el.firstElementChild) {
      this.$el.insertBefore(this.mapContainer, this.$el.firstElementChild);
    } else {
      this.$el.appendChild(this.mapContainer);
    }
    this.mapContainer.style.visibility = 'visible';
    this.scope = {
      map: this.map,
      mapGetter: () => this.map,
    };
    this.ready = true;
    setTimeout(() => {
      this.$emit('ready', this.scope);
    }, 30);

    const fullscreen = useFullscreen();
    this.$watch(
      () => fullscreen.isFullscreen,
      () => {
        if (this.map) {
          let currentZoom = this.map.getZoom();
          this.map.setZoom(fullscreen.isFullscreen ? ++currentZoom : --currentZoom);
        }
      },
      { immediate: false }
    );
  },
  unmounted() {
    this.destroy();
  },
  methods: {
    destroy() {
      if (this.map) {
        this.map.destroy();
        this.map = null;
      }
    },
  },
  render() {
    return h(
      'div',
      { class: 'map-core', style: 'position: relative; width: 100%; height: 100%' },
      this.ready === true && this.$slots.default ? this.$slots.default(this.scope) : null
    );
  },
};
</script>

<style lang="less">
.map-core {
  .amap-logo,
  .amap-copyright {
    display: none !important;
  }
}
</style>
